import api from '@/pages/measurements/api'
import { getData } from '@/servers/http'
import { Toast } from 'antd-mobile-v2'
import React, { useEffect, useState } from 'react'
import { history } from 'umi'

import { DIMENSION_TYPE } from './dict'

export default function (eval_id, result_id) {
    // 展开状态
    const [expand, setExpand] = useState(true)
    // 测评信息
    const [evalInfo, setEvalInfo] = useState(null)
    // 测评基本信息
    const [info, setInfo] = useState(null)
    // 测评结果信息
    const [resultList, setResultList] = useState([])
    // 测评提交时间
    const [createTime, setCreateTime] = useState('')
    // 雷达图总分
    const [dimensionScore, setDimensionScore] = useState([{}])
    // 雷达图得分
    const [myScore, setMyScore] = useState([{}])
    // 环形图数据
    const [pieData, setPieData] = useState([])
    // 数据与你相同比例
    const [rate, setRate] = useState(0)
    // Canvas 分享图 实例
    const posterRef = React.createRef()
    // 分享图信息
    const [shareInfo, setShareInfo] = useState(null)
    // 结果ID，用于获取推荐课程
    const [infoId, setInfoId] = useState(0)
    // 发布状态 1-上架 0-下架
    const [publishStatus, setPublishStatus] = useState('1')
    // 分享弹窗可视状态
    const [shareModalVisible, setShareModalVisible] = useState(false)
    // 总分
    const [totalScore, setTotalScore] = useState(-1)

    useEffect(() => {
        if (result_id) {
            getResultById(result_id)
        } else {
            getResult()
        }
    }, [])

    // 根据结果ID获取测评结果
    const getResultById = async id => {
        const res = (await getData(`${api.testEvalsRecordView}${id}`)) || {}
        const { status, data } = res
        if (status !== 200) return
        data && updataData(data)
    }

    // 获取最新测评结果
    const getResult = () => {
        let result = JSON.parse(localStorage.getItem('measurement_result') || '{}')
        console.log(result)
        const { testEval } = result || {}
        if (Object.keys(testEval).length === 0) return
        testEval && updataData(testEval)
    }

    // 更新结果数据
    const updataData = data => {
        const { evalInfo, create_time, info, dimensionScore, myScore, analysis, rate, lists, publish_status, sum_score } = data
        setInfo(info)
        setInfoId(info?.id)
        setEvalInfo(evalInfo)
        setCreateTime(create_time)
        updateDimensionScore(dimensionScore, myScore)
        updateMyScore(myScore)
        updatePieData(analysis)
        setRate(rate)
        setResultList(lists)
        setPublishStatus(publish_status)
        setTotalScore(sum_score)

        const userInfo = localStorage['career_fe_user'] ? JSON.parse(localStorage['career_fe_user']) : {}

        let keyword = typeof info?.keyword === 'string' ? info?.keyword : info?.keyword?.join(' ')
        setShareInfo({
            id: evalInfo?.id,
            userName: userInfo?.name,
            examName: evalInfo?.name || '职业测评',
            avatar: userInfo?.avatar,
            cover: info?.cover,
            type: info?.type,
            name: info?.name || '未知',
            // 测评类型
            dimensionTYpe: evalInfo?.dimension_type,
            // 分数（总分规则题）
            score: evalInfo?.dimension_type === DIMENSION_TYPE.TotalScore ? sum_score : '',
            // 职场小测分享图不显示关键字
            keyword: evalInfo?.dimension_type === DIMENSION_TYPE.Custom ? '' : keyword,
        })
    }

    // 设置雷达图总分
    const updateDimensionScore = (data, result) => {
        let tmpDimensionScore = []
        data?.map((item, index) => {
            let score = { name: item.name, max: item.score, value: `${result[index]?.value}分` }
            tmpDimensionScore.push(score)
        })
        tmpDimensionScore.length === 0 && (tmpDimensionScore = [{ name: '-' }, { name: '-' }, { name: '-' }])
        setDimensionScore(tmpDimensionScore)
    }

    // 设置雷达图得分
    const updateMyScore = data => {
        let tmpMyScore = []
        data?.map(item => {
            tmpMyScore.push(item.value)
        })
        tmpMyScore.length === 0 && (tmpMyScore = [0, 0, 0])
        setMyScore(tmpMyScore)
    }

    // 设置饼图数据
    const updatePieData = data => {
        let tmpPieData = []
        data?.map(item => {
            tmpPieData.push(item)
        })
        setPieData(tmpPieData)
    }

    // 切换展开状态
    const toggleExpand = () => {
        setExpand(!expand)
    }

    // 再测一次
    const reExam = () => {
        // if (publishStatus === '0') {
        //     Toast.fail('该测评已下架！')
        //     return
        // }
        let result = JSON.parse(localStorage.getItem('measurement_result') || '{}')
        const { scene_id } = result || {}
        history.replace(`/level?id=${scene_id}`)
        // wx.miniProgram.postMessage({
        //     data: scene_id,
        // })
        // wx.miniProgram.navigateBack({
        //     success:(res)=>{
        //         console.log(res)
        //     },
        //     fail:(err)=>{
        //         console.log(err)
        //     },
        // })
    }

    // 去详情
    const toDetail = () => {
        history.push(`/measurements/${evalInfo?.id}`)
    }

    return {
        info,
        evalInfo,
        resultList,
        createTime,
        dimensionScore,
        myScore,
        pieData,
        reExam,
        expand,
        toggleExpand,
        rate,
        posterRef,
        shareInfo,
        shareModalVisible,
        setShareModalVisible,
        toDetail,
        totalScore,
    }
}
